//
//  GoodsDetailsViewController.m
//  Findif
//
//  Created by Cicel Chen on 2018/10/22.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "GoodsDetailsViewController.h"
#import "GoodsDetailsHeaderView.h"
#import "HomeTableViewCell.h"
#import "MomentCell.h"
#import "Moment.h"
#import "Comment.h"
#import <CommonCrypto/CommonDigest.h>
#import "SureOrderViewController.h"
#import "PersonalViewController.h"
#import "NormalSureOrderViewController.h"
#import "GoodsInfoTableViewCell.h"
#import "MapTableViewCell.h"
#import "NewCouponTableViewCell.h"
#import "CouponModel.h"
#import "CalenderViewController.h"
#import "TuanGoodsDetailsHeaderView.h"
#import "ShowTuanWeek.h"
#import <JMessage/JMessage.h>
#import "ChatRoomViewController.h"
#import "WXApi.h"
#import "CommitDetailsViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "MapViewController.h"
#import "CreateActiveDetailsViewController.h"
#import "FinishPersonalView.h"

@interface GoodsDetailsViewController ()<UITableViewDelegate,UITableViewDataSource,MomentCellDelegate,GoodsDetailsHeaderViewDelegate,CalenderViewControllerDelegate,FinishPersonalViewDelegate>{
    
    dispatch_source_t _timer;
}


@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UIView * navView;
@property (nonatomic, weak)UILabel * titleLabel;
@property (nonatomic, strong)UIButton * backButton;
@property (nonatomic, strong)UIButton * collectButton;
@property (nonatomic, strong)UIButton * shareButton;
@property (nonatomic, strong)NSArray<Moment*> *momentList;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, weak)UILabel * moneyLabel;
@property (nonatomic, weak)UILabel * originalLabel;
@property (nonatomic, weak)UILabel * exploreLabel;
@property (nonatomic, weak)UILabel * timeCountlLabel;
//@property (nonatomic, weak)UILabel * countdownLabel;
//@property (nonatomic, weak)UILabel * endUpLabel;
//@property (nonatomic, weak)UILabel * countdownValueLabel;
//@property (nonatomic, weak)UILabel * endUpValueLabel;
@property (nonatomic, weak)UIButton * buyButton;

@property (nonatomic, strong)NSDictionary * dataDict;
@property (nonatomic, strong)GoodsDetailsHeaderView * headerView;
@property (nonatomic, strong)TuanGoodsDetailsHeaderView * tuanView;

@property (nonatomic, weak)UIToolbar *toolbar;
@property (nonatomic, weak)UIView * couponView;
@property (nonatomic, weak)UITableView * couponTableView;
@property (nonatomic, strong)NSArray<CouponModel *> * couponArray;
@property (nonatomic, strong)NSArray<ShowTuanWeek *> * tuanArray;
@property (nonatomic, copy)NSString * dateString;
@property (nonatomic, copy)NSString * timeString;
@property (nonatomic, weak)UILabel * showLabel;
@property (nonatomic, copy)NSString * orderTimeString;

@property (nonatomic, weak)UIToolbar * shareToolbar;
@property (nonatomic, weak)UIView * shareView;
@property (nonatomic, assign)float cellHeight;
@property (nonatomic, copy)NSString * start;
@property (nonatomic, copy)NSString * distance;

//店铺纬度
@property (nonatomic, copy)NSString * merchants_latitude;
//店铺经度
@property (nonatomic, copy)NSString * merchants_longitude;
//店铺名称
@property (nonatomic, copy)NSString * merchants_name;
//店铺地址
@property (nonatomic, copy)NSString * merchants_local;

@property (nonatomic, copy)NSString * local;


@property (nonatomic, weak)UIToolbar * finishToolbar;
@property (nonatomic, strong)FinishPersonalView * finishView;
@property (nonatomic, assign)int is_official;
@property (nonatomic, copy)NSString * merchants_goods_field_time;

@end

@implementation GoodsDetailsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ZRWhiteColor;
    
    //    NSDate *date=[NSDate date];
    //    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    //    [format1 setDateFormat:@"yyyy-MM-dd"];
    //    NSString *dateStr;
    //    dateStr=[format1 stringFromDate:date];
    //    self.dateString = dateStr;
    
    [self setupNSNoti];
    [self setupNav];
    [self loadData];
    [self initTestInfo];
    [self setupUI];
}

- (void)setupNSNoti{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PushToChat) name:@"PushToChat" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToCalendarView) name:@"pushToCalendarView" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickTuanMoreButton:) name:@"clickTuanMoreButton" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSelectTime:) name:@"updateSelectTime" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showAlertView) name:@"showAlertView" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCellHeight:) name:@"changeCellHeight" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToPersonal:) name:@"pushToPersonal" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToMapView) name:@"pushToMapView" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToMapView) name:@"PushToNavViewController" object:nil];
}

- (void)setTuanArray:(NSArray<ShowTuanWeek *> *)tuanArray{
    
    _tuanArray = tuanArray;
    
    self.tuanView.tuanArray = tuanArray;
    [self.tableView reloadData];
}

- (void)setDateString:(NSString *)dateString{
    
    _dateString = dateString;
    
    self.tuanView.dateStr = dateString;
    [self.tableView reloadData];
}


- (void)loadData{
    
    //获取当前时间日期
    NSDate *date=[NSDate date];
    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr;
    dateStr=[format1 stringFromDate:date];
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    NSDictionary * dict = @{@"timeStamp":dateStr,@"goods_id":self.ID,@"user_id":user_id};
    
    NSString * sign = [self signStr:dict];
    
    NSDictionary * resDict = @{@"timeStamp":dateStr,@"sign":sign,@"goods_id":self.ID,@"user_id":user_id};
    
    [[NetworkTool sharedTools] POST:@"Api/getGoodsInfo" parameters:resDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
//        NSLog(@"res===%@",responseObject);
        
        NSDictionary * dict = responseObject[@"data"];
        
        self.dataDict = dict;
        
//        NSLog(@"dict===%@",dict);
        //是否收藏  1为是 0为否
        int isCollect = [dict[@"is_collection"] intValue];
        
        if (isCollect == 1) {
            
            self.collectButton.selected = YES;
        }else{
            
            self.collectButton.selected = NO;
        }
        
        double lat = [dict[@"merchants_latitude"] doubleValue];
        double lon = [dict[@"merchants_longitude"] doubleValue];
        
        double userLat = [DEF_GET_OBJECT(@"lat") doubleValue];
        double userLon = [DEF_GET_OBJECT(@"lon") doubleValue];
        
        double res = [self distanceBetweenOrderBy:lat :userLat :lon :userLon];
        if (res > 1000) {
            
            res = res / 1000;
            self.distance = [NSString stringWithFormat:@"%.2fkm",res];
        }else{
            
            self.distance = [NSString stringWithFormat:@"%.2fm",res];
        }
        
        self.dateString = [NSString stringWithFormat:@"%@",dict[@"merchants_goods_available_time_now_day"]];
        self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",dict[@"merchatns_goods_platform_discount_price"]];
        //        self.originalLabel.text = [NSString stringWithFormat:@"￥%@",dict[@"merchants_goods_price"]];
        NSString * orString = [NSString stringWithFormat:@"￥%@",dict[@"merchatns_goods_platform_price"]];
        //中划线
        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:orString attributes:attribtDic];
        
        self.originalLabel.attributedText = attribtStr;
        
        int merchants_goods_is_need_insurance = [self.dataDict[@"merchants_goods_is_need_insurance"] intValue];
        
        
        NSString * merchants_goods_merchants_id = [NSString stringWithFormat:@"%@",self.dataDict[@"merchants_goods_merchants_id"]];
        
        NSString * startTime = [NSString stringWithFormat:@"%@",self.dataDict[@"merchants_goods_start_time"]];
        NSString * endTime = [NSString stringWithFormat:@"%@",self.dataDict[@"merchants_goods_end_time"]];
        
        // 当前时间的时间戳
        NSString *nowStr = [self getCurrentTimeyyyymmdd];
        // 计算时间差值
        NSInteger secondsCountDown = [self getDateDifferenceWithNowDateStr:nowStr deadlineStr:startTime];
        
        self.is_official = [dict[@"is_official"] intValue];
        
        if (self.is_official == 1) {
            
            self.merchants_latitude = [NSString stringWithFormat:@"%@",dict[@"merchants_goods_address_latitude"]];
            self.merchants_longitude = [NSString stringWithFormat:@"%@",dict[@"merchants_goods_address_longitude"]];
            self.merchants_local = dict[@"merchants_goods_address"];
            self.merchants_name = dict[@"merchants_name"];
            self.local = [NSString stringWithFormat:@"%@,%@",dict[@"merchants_goods_address_latitude"],dict[@"merchants_goods_address_longitude"]];
        }else{
            
            self.merchants_latitude = [NSString stringWithFormat:@"%@",dict[@"merchants_latitude"]];
            self.merchants_longitude = [NSString stringWithFormat:@"%@",dict[@"merchants_longitude"]];
            self.merchants_local = dict[@"merchants_address"];
            self.merchants_name = dict[@"merchants_name"];
            self.local = [NSString stringWithFormat:@"%@,%@",dict[@"merchants_latitude"],dict[@"merchants_longitude"]];
        }
        
        
        self.merchants_goods_field_time = [NSString stringWithFormat:@"%@",dict[@"merchants_goods_field_time"]];
        
        if (merchants_goods_is_need_insurance == 1) {
            //1为官方 0不是官方
            if (secondsCountDown > 0) {
                //还未开始
                
                [self.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.mas_equalTo(self.bottomView);
                    make.top.mas_equalTo(self.bottomView).offset(13 * SCREENH6);
                }];
                
                [self.originalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.mas_equalTo(self.moneyLabel);
                    make.top.mas_equalTo(self.moneyLabel.mas_bottom).offset(2 * SCREENH6);
                }];
                
                self.timeCountlLabel.hidden = YES;
                self.exploreLabel.hidden = YES;

            }else{
                //已经开始
                self.start = @"start";
                self.buyButton.selected = NO;
                
                self.exploreLabel.text = @"距结束";
                
                if ([self.state isEqualToString:@"create"]) {
                    
                    [self.buyButton setBackgroundColor:ColorWithRGB(0xFF5C5C)];
                    [self.buyButton setTitle:@"发起活动" forState:UIControlStateNormal];
                }else{
                    
                    [self.buyButton setBackgroundColor:ColorWithRGB(0xFFE055)];
                    [self.buyButton setTitle:@"购买" forState:UIControlStateNormal];
                }
                secondsCountDown = [self getDateDifferenceWithNowDateStr:nowStr deadlineStr:endTime];
                __weak __typeof(self) weakSelf = self;
                
                if (self->_timer == nil) {
                    __block NSInteger timeout = secondsCountDown; // 倒计时时间
                    
                    if (timeout!=0) {
                        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                        self->_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
                        dispatch_source_set_timer(self->_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC,  0); //每秒执行
                        dispatch_source_set_event_handler(self->_timer, ^{
                            if(timeout <= 0){ //  当倒计时结束时做需要的操作: 关闭 活动到期不能提交
                                dispatch_source_cancel(self->_timer);
                                self->_timer = nil;
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    weakSelf.timeCountlLabel.text = @"00:00:00";
                                });
                            } else { // 倒计时重新计算 时/分/秒
                                NSInteger days = (int)(timeout/(3600*24));
                                NSInteger hours = (int)((timeout-days*24*3600)/3600);
                                NSInteger minute = (int)(timeout-days*24*3600-hours*3600)/60;
                                NSInteger second = timeout - days*24*3600 - hours*3600 - minute*60;
                                NSString *strTime = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hours, minute, second];
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    if (days == 0) {
                                        
                                        weakSelf.timeCountlLabel.text = strTime;
                                        
                                        [weakSelf.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.leading.mas_equalTo(self.bottomView).offset(10 * SCREENH6);
                                            make.top.mas_equalTo(self.bottomView).offset(13 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.originalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.centerX.mas_equalTo(self.moneyLabel);
                                            make.top.mas_equalTo(self.moneyLabel.mas_bottom).offset(2 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.timeCountlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.trailing.mas_equalTo(self.bottomView).offset(-5 * SCREENH6);
                                            make.width.mas_equalTo(63 * SCREENH6);
                                            make.centerY.mas_equalTo(self.bottomView);
                                        }];
                                        
                                        [weakSelf.exploreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.trailing.mas_equalTo(self.timeCountlLabel.mas_leading).offset(-5 * SCREENH6);
                                            make.centerY.mas_equalTo(self.timeCountlLabel);
                                        }];
                                    }else if(days > 30){
                                        
                                        weakSelf.timeCountlLabel.text = [NSString stringWithFormat:@">30天\n%02ld:%02ld:%02ld",hours, minute, second];
                                        
                                        [weakSelf.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.centerX.mas_equalTo(self.bottomView);
                                            make.top.mas_equalTo(self.bottomView).offset(13 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.originalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.centerX.mas_equalTo(self.moneyLabel);
                                            make.top.mas_equalTo(self.moneyLabel.mas_bottom).offset(2 * SCREENH6);
                                        }];
                                        
                                        weakSelf.timeCountlLabel.hidden = YES;
                                        weakSelf.exploreLabel.hidden = YES;
                                    }else{
                                        
                                        weakSelf.timeCountlLabel.text = [NSString stringWithFormat:@"%ld天\n%02ld:%02ld:%02ld", days, hours, minute, second];
                                        
                                        [weakSelf.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.leading.mas_equalTo(self.bottomView).offset(10 * SCREENH6);
                                            make.top.mas_equalTo(self.bottomView).offset(13 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.originalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.centerX.mas_equalTo(self.moneyLabel);
                                            make.top.mas_equalTo(self.moneyLabel.mas_bottom).offset(2 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.timeCountlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.trailing.mas_equalTo(self.bottomView).offset(-5 * SCREENH6);
                                            make.width.mas_equalTo(63 * SCREENH6);
                                            make.centerY.mas_equalTo(self.bottomView);
                                        }];
                                        
                                        [weakSelf.exploreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.trailing.mas_equalTo(self.timeCountlLabel.mas_leading).offset(-5 * SCREENH6);
                                            make.centerY.mas_equalTo(self.timeCountlLabel);
                                        }];
                                    }
                                    
                                });
                                timeout--; // 递减 倒计时-1(总时间以秒来计算)
                            }
                        });
                        dispatch_resume(self->_timer);
                    }
                }
            }
        }else{
            
            if (secondsCountDown > 0) {
                //还未开始
                self.start = @"noStart";
                self.buyButton.selected = YES;
                [self.buyButton setBackgroundColor:ColorWithRGB(0x53d499)];
                self.exploreLabel.text = @"距开抢";
                int is_open_group_reminded = [self.dataDict[@"is_open_group_reminded"] intValue];
                if (is_open_group_reminded == 1) {
                    
                    [self.buyButton setTitle:@"已预约" forState:UIControlStateNormal];
                }else{
                    
                    [self.buyButton setTitle:@"开抢提醒" forState:UIControlStateNormal];
                }
                
                __weak __typeof(self) weakSelf = self;
                
                if (self->_timer == nil) {
                    __block NSInteger timeout = secondsCountDown; // 倒计时时间
                    
                    if (timeout!=0) {
                        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                        self->_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
                        dispatch_source_set_timer(self->_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC,  0); //每秒执行
                        dispatch_source_set_event_handler(self->_timer, ^{
                            if(timeout <= 0){ //  当倒计时结束时做需要的操作: 关闭 活动到期不能提交
                                dispatch_source_cancel(self->_timer);
                                self->_timer = nil;
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    weakSelf.timeCountlLabel.text = @"00:00:00";
                                });
                            } else { // 倒计时重新计算 时/分/秒
                                NSInteger days = (int)(timeout/(3600*24));
                                NSInteger hours = (int)((timeout-days*24*3600)/3600);
                                NSInteger minute = (int)(timeout-days*24*3600-hours*3600)/60;
                                NSInteger second = timeout - days*24*3600 - hours*3600 - minute*60;
                                NSString *strTime = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hours, minute, second];
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    if (days == 0) {
                                        weakSelf.timeCountlLabel.text = strTime;
                                    } else {
                                        weakSelf.timeCountlLabel.text = [NSString stringWithFormat:@"%ld天\n%02ld:%02ld:%02ld", days, hours, minute, second];
                                    }
                                    
                                });
                                timeout--; // 递减 倒计时-1(总时间以秒来计算)
                            }
                        });
                        dispatch_resume(self->_timer);
                    }
                }
                
                [self.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.leading.mas_equalTo(self.bottomView).offset(10 * SCREENH6);
                    make.top.mas_equalTo(self.bottomView).offset(13 * SCREENH6);
                }];
                
                [self.originalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.mas_equalTo(self.moneyLabel);
                    make.top.mas_equalTo(self.moneyLabel.mas_bottom).offset(2 * SCREENH6);
                }];
                
                [self.timeCountlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.trailing.mas_equalTo(self.bottomView).offset(-5 * SCREENH6);
                    make.width.mas_equalTo(63 * SCREENH6);
                    make.centerY.mas_equalTo(self.bottomView);
                }];
                
                [self.exploreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.trailing.mas_equalTo(self.timeCountlLabel.mas_leading).offset(-5 * SCREENH6);
                    make.centerY.mas_equalTo(self.timeCountlLabel);
                }];
            }else{
                //已经开始
                self.start = @"start";
                self.buyButton.selected = NO;
                
                self.exploreLabel.text = @"距结束";
                
                if ([self.state isEqualToString:@"create"]) {
                    
                    [self.buyButton setBackgroundColor:ColorWithRGB(0xFF5C5C)];
                    [self.buyButton setTitle:@"发起活动" forState:UIControlStateNormal];
                }else{
                    
                    [self.buyButton setBackgroundColor:ColorWithRGB(0xFFE055)];
                    [self.buyButton setTitle:@"购买" forState:UIControlStateNormal];
                }
                secondsCountDown = [self getDateDifferenceWithNowDateStr:nowStr deadlineStr:endTime];
                __weak __typeof(self) weakSelf = self;
                
                if (self->_timer == nil) {
                    __block NSInteger timeout = secondsCountDown; // 倒计时时间
                    
                    if (timeout!=0) {
                        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                        self->_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
                        dispatch_source_set_timer(self->_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC,  0); //每秒执行
                        dispatch_source_set_event_handler(self->_timer, ^{
                            if(timeout <= 0){ //  当倒计时结束时做需要的操作: 关闭 活动到期不能提交
                                dispatch_source_cancel(self->_timer);
                                self->_timer = nil;
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    weakSelf.timeCountlLabel.text = @"00:00:00";
                                });
                            } else { // 倒计时重新计算 时/分/秒
                                NSInteger days = (int)(timeout/(3600*24));
                                NSInteger hours = (int)((timeout-days*24*3600)/3600);
                                NSInteger minute = (int)(timeout-days*24*3600-hours*3600)/60;
                                NSInteger second = timeout - days*24*3600 - hours*3600 - minute*60;
                                NSString *strTime = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hours, minute, second];
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    if (days == 0) {
                                        
                                        weakSelf.timeCountlLabel.text = strTime;
                                        
                                        [weakSelf.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.leading.mas_equalTo(self.bottomView).offset(10 * SCREENH6);
                                            make.top.mas_equalTo(self.bottomView).offset(13 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.originalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.centerX.mas_equalTo(self.moneyLabel);
                                            make.top.mas_equalTo(self.moneyLabel.mas_bottom).offset(2 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.timeCountlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.trailing.mas_equalTo(self.bottomView).offset(-5 * SCREENH6);
                                            make.width.mas_equalTo(63 * SCREENH6);
                                            make.centerY.mas_equalTo(self.bottomView);
                                        }];
                                        
                                        [weakSelf.exploreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.trailing.mas_equalTo(self.timeCountlLabel.mas_leading).offset(-5 * SCREENH6);
                                            make.centerY.mas_equalTo(self.timeCountlLabel);
                                        }];
                                    }else if(days > 30){
                                        
                                        weakSelf.timeCountlLabel.text = [NSString stringWithFormat:@">30天\n%02ld:%02ld:%02ld",hours, minute, second];
                                        
                                        [weakSelf.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.centerX.mas_equalTo(self.bottomView);
                                            make.top.mas_equalTo(self.bottomView).offset(13 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.originalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.centerX.mas_equalTo(self.moneyLabel);
                                            make.top.mas_equalTo(self.moneyLabel.mas_bottom).offset(2 * SCREENH6);
                                        }];
                                        
                                        weakSelf.timeCountlLabel.hidden = YES;
                                        weakSelf.exploreLabel.hidden = YES;
                                    }else{
                                        
                                        weakSelf.timeCountlLabel.text = [NSString stringWithFormat:@"%ld天\n%02ld:%02ld:%02ld", days, hours, minute, second];
                                        
                                        [weakSelf.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.leading.mas_equalTo(self.bottomView).offset(10 * SCREENH6);
                                            make.top.mas_equalTo(self.bottomView).offset(13 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.originalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.centerX.mas_equalTo(self.moneyLabel);
                                            make.top.mas_equalTo(self.moneyLabel.mas_bottom).offset(2 * SCREENH6);
                                        }];
                                        
                                        [weakSelf.timeCountlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.trailing.mas_equalTo(self.bottomView).offset(-5 * SCREENH6);
                                            make.width.mas_equalTo(63 * SCREENH6);
                                            make.centerY.mas_equalTo(self.bottomView);
                                        }];
                                        
                                        [weakSelf.exploreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                                            make.trailing.mas_equalTo(self.timeCountlLabel.mas_leading).offset(-5 * SCREENH6);
                                            make.centerY.mas_equalTo(self.timeCountlLabel);
                                        }];
                                    }
                                    
                                });
                                timeout--; // 递减 倒计时-1(总时间以秒来计算)
                            }
                        });
                        dispatch_resume(self->_timer);
                    }
                }
            }
        }
        
        
        
        [self loadCouponDataWithShop_id:merchants_goods_merchants_id];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
    [[ZRNetworkTool sharedTool] getGoodsCommentsListResultWithGoodsID:self.ID WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            self.momentList = [NSArray yy_modelArrayWithClass:[Moment class] json:responseData[@"data"]];
        }
    }];
    
    
}

- (void)setLocal:(NSString *)local{
    
    _local = local;
    
    [self.tableView reloadData];
}

- (void)loadCouponDataWithShop_id:(NSString *)shop_id{
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    [[ZRNetworkTool sharedTool] getMerchantsCouponsResultWithShop_id:shop_id WithUser_id:user_id WithBlock:^(BOOL success, id responseData) {
        
        //        NSLog(@"res===%@",responseData);
        if (success) {
            
            self.couponArray = [NSArray yy_modelArrayWithClass:[CouponModel class] json:responseData[@"data"]];
        }
    }];
}


-(void)setCouponArray:(NSArray<CouponModel *> *)couponArray{
    
    _couponArray = couponArray;
    
    [self.couponTableView reloadData];
}

- (void)setDataDict:(NSDictionary *)dataDict{
    
    _dataDict = dataDict;
    
    if ([self.infoType isEqualToString:@"1"]) {
        
        self.headerView.dict = dataDict;
    }else{
        
        self.tuanView.dict = dataDict;
        
        NSArray * merchants_goods_available_time_arr = dataDict[@"merchants_goods_available_time_arr"];
        
        if (merchants_goods_available_time_arr.count == 0 || merchants_goods_available_time_arr.count == 1) {
            
            self.tuanView.height = 615 * SCREENH6;
        }else{
            
            self.tuanView.height = 615 * SCREENH6 + 50 * (merchants_goods_available_time_arr.count - 1)* SCREENH6;
        }
    }
    [self.tableView reloadData];
}




- (void)setMomentList:(NSArray<Moment *> *)momentList{
    
    _momentList = momentList;
    
    [self.tableView reloadData];
}


#pragma mark - 测试数据
- (void)initTestInfo
{
    //    self.momentList = [[NSMutableArray alloc] init];
    //    NSMutableArray *commentList = nil;
    //    for (int i = 0;  i < 2; i ++)  {
    //        // 评论
    //        commentList = [[NSMutableArray alloc] init];
    //
    //        Moment *moment = [[Moment alloc] init];
    //        moment.userName = @"Jeanne";
    //        moment.singleWidth = 500;
    //        moment.singleHeight = 315;
    //        moment.text = @"天界大乱，九州屠戮，当初被推下地狱的她已经浴火归来 😭😭剑指仙界'你们杀了他，我便覆了你的天，毁了你的界，永世不得超生又如何！'👍👍 ";
    //        moment.fileCount = arc4random()%10;
    //        [self.momentList addObject:moment];
    //    }
}

- (void)setupNav{
    
    UIView * navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kStatusBarHeight + kNavHeight)];
    
    navView.backgroundColor = ColorWithRGB(0xF3F3F0);
    navView.userInteractionEnabled = YES;
    
    self.navView = navView;
    
    [self.view addSubview:self.navView];
    
    
    self.collectButton = [self setupButtonWithImage:@"star(4)"];
    self.collectButton.selected = NO;
    [self.collectButton setImage:[UIImage imageNamed:@"形状3"] forState:UIControlStateSelected];
    [self.navView addSubview:self.collectButton];
    self.shareButton = [self setupButtonWithImage:@"share"];
    [self.navView addSubview:self.shareButton];
    self.backButton = [self setupButtonWithImage:@"back"];
    [self.navView addSubview:self.backButton];
    
    UILabel * titleLabel = [UILabel new];
    
    if ([self.state isEqualToString:@"create"]) {
        
        titleLabel.text = @"创建活动";
    }else{
        
        titleLabel.text = @"详情";
    }
    
    titleLabel.textColor = ZRBlackColor;
    titleLabel.font = [UIFont boldSystemFontOfSize:17 * SCREENH6];
    
    self.titleLabel = titleLabel;
    
    [self.navView addSubview:self.titleLabel];
    
}

- (void)viewDidLayoutSubviews{
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.navView).offset(kStatusBarHeight + 10 * SCREENH6);
    }];
    
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(5 * SCREENH6);
        make.centerY.mas_equalTo(self.titleLabel);
    }];
    
    [self.shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.view).offset(-20 * SCREENH6);
        make.centerY.mas_equalTo(self.backButton);
    }];
    
    [self.collectButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.shareButton.mas_leading).offset(-15 * SCREENH6);
        make.centerY.mas_equalTo(self.shareButton);
    }];
    
    //    [self.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.leading.mas_equalTo(self.bottomView).offset(10 * SCREENH6);
    //        make.top.mas_equalTo(self.bottomView).offset(13 * SCREENH6);
    //    }];
    //
    //    [self.originalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerX.mas_equalTo(self.moneyLabel);
    //        make.top.mas_equalTo(self.moneyLabel.mas_bottom).offset(2 * SCREENH6);
    //    }];
    //
    //    [self.timeCountlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.trailing.mas_equalTo(self.bottomView).offset(-5 * SCREENH6);
    //        make.width.mas_equalTo(63 * SCREENH6);
    //        make.centerY.mas_equalTo(self.bottomView);
    //    }];
    //
    //    [self.exploreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.trailing.mas_equalTo(self.timeCountlLabel.mas_leading).offset(-5 * SCREENH6);
    //        make.centerY.mas_equalTo(self.timeCountlLabel);
    //    }];
    
    //    [self.countdownLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.mas_equalTo(self.bottomView).offset(12 * SCREENH6);
    //        make.leading.mas_equalTo(self.moneyLabel.mas_trailing).offset(20 * SCREENH6);
    //    }];
    //
    //    [self.countdownValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerY.mas_equalTo(self.countdownLabel);
    //        make.leading.mas_equalTo(self.countdownLabel.mas_trailing).offset(5 * SCREENH6);
    //    }];
    //
    //    [self.endUpLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.mas_equalTo(self.countdownLabel.mas_bottom).offset(3 * SCREENH6);
    //        make.leading.mas_equalTo(self.countdownLabel);
    //    }];
    //
    //    [self.endUpValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerY.mas_equalTo(self.endUpLabel);
    //        make.leading.mas_equalTo(self.endUpLabel.mas_trailing).offset(5 * SCREENH6);
    //    }];
    
    [self.buyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.view);
        make.leading.mas_equalTo(self.bottomView.mas_trailing);
        make.height.centerY.mas_equalTo(self.bottomView);
    }];
}

- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kStatusBarHeight + kNavHeight, kScreenW, kScreenH - kStatusBarHeight - kNavHeight - 60 * SCREENH6 -kBarHeight) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF8F9FA);
    //    tableView.rowHeight = 120 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.separatorInset = UIEdgeInsetsZero;
    
    if ([self.infoType isEqualToString:@"1"]) {
        
        self.headerView =  [[GoodsDetailsHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 590 * SCREENH6)];
        // 设置header
        self.headerView.goodsDetailsHeaderViewDelegate = self;
        tableView.tableHeaderView = self.headerView;
    }else{
        
        self.tuanView =  [[TuanGoodsDetailsHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 665 * SCREENH6)];
        // 设置header
        //        self.tuanView.tuanDetailsHeaderViewDelegate = self;
        tableView.tableHeaderView = self.tuanView;
    }
    self.tableView = tableView;
    
    [self.tableView registerClass:[MomentCell class] forCellReuseIdentifier:@"GoodsDetailCell"];
    [self.tableView registerClass:[GoodsInfoTableViewCell class] forCellReuseIdentifier:@"GoodsInfoTableViewCell"];
    [self.tableView registerClass:[MapTableViewCell class] forCellReuseIdentifier:@"MapTableViewCell"];
    
    [self.view addSubview:self.tableView];
    
    
    UIView * bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH - 60 * SCREENH6 - kBarHeight, 225 * SCREENH6, 60 * SCREENH6)];
    
    bottomView.backgroundColor = ZRBlackColor;
    //    bottomView.userInteractionEnabled = YES;
    
    self.bottomView = bottomView;
    
    [self.view addSubview:self.bottomView];
    
    
    UILabel * moneyLabel = [UILabel new];
    
    moneyLabel.textColor = ColorWithRGB(0xFFE055);
    moneyLabel.text = @"----";
    moneyLabel.font = [UIFont boldSystemFontOfSize:16 * SCREENH6];
    moneyLabel.textAlignment = NSTextAlignmentCenter;
    
    self.moneyLabel = moneyLabel;
    
    [self.bottomView addSubview:self.moneyLabel];
    
    UILabel * originalLabel = [UILabel new];
    
    originalLabel.textColor = ZRWhiteColor;
    originalLabel.text = @"----";
    originalLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    originalLabel.textAlignment = NSTextAlignmentCenter;
    
    self.originalLabel = originalLabel;
    
    [self.bottomView addSubview:self.originalLabel];
    
    UILabel * exploreLabel = [UILabel new];
    
    exploreLabel.textColor = ZRWhiteColor;
    exploreLabel.text = @"----";
    exploreLabel.font = [UIFont systemFontOfSize:12 * SCREENH6];
    exploreLabel.textAlignment = NSTextAlignmentRight;
    
    self.exploreLabel = exploreLabel;
    
    [self.bottomView addSubview:self.exploreLabel];
    
    UILabel * timeCountlLabel = [UILabel new];
    
    timeCountlLabel.textColor = ColorWithRGB(0xff5c5c);
    timeCountlLabel.text = @"----";
    timeCountlLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    timeCountlLabel.numberOfLines = 0;
    timeCountlLabel.textAlignment = NSTextAlignmentCenter;
    
    self.timeCountlLabel = timeCountlLabel;
    
    [self.bottomView addSubview:self.timeCountlLabel];
    
    
    //    UILabel * countdownLabel = [UILabel new];
    //
    //    countdownLabel.textColor = ZRWhiteColor;
    //    countdownLabel.text = @"倒计时";
    //    countdownLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    //
    //    self.countdownLabel = countdownLabel;
    //
    //    [self.bottomView addSubview:self.countdownLabel];
    //
    //
    //    UILabel * endUpLabel = [UILabel new];
    //
    //    endUpLabel.textColor = ZRWhiteColor;
    //    endUpLabel.text = @"过期";
    //    endUpLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    //
    //    self.endUpLabel = endUpLabel;
    //
    //    [self.bottomView addSubview:self.endUpLabel];
    //
    //
    //    UILabel * countdownValueLabel = [UILabel new];
    //
    //    countdownValueLabel.textColor = [UIColor redColor];
    //    countdownValueLabel.text = @"1:12:12";
    //    countdownValueLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    //
    //    self.countdownValueLabel = countdownValueLabel;
    //
    //    [self.bottomView addSubview:self.countdownValueLabel];
    //
    //
    //    UILabel * endUpValueLabel = [UILabel new];
    //
    //    endUpValueLabel.textColor = [UIColor redColor];
    //    endUpValueLabel.text = @"3天";
    //    endUpValueLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    //
    //    self.endUpValueLabel = endUpValueLabel;
    //
    //    [self.bottomView addSubview:self.endUpValueLabel];
    
    
    UIButton * buyButton = [UIButton new];
    
    if ([self.state isEqualToString:@"create"]) {
        
        [buyButton setTitle:@"发起活动" forState:UIControlStateNormal];
        [buyButton setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
        [buyButton setBackgroundColor:ColorWithRGB(0xFF5C5C)];
    }else{
        
        [buyButton setTitle:@"购买" forState:UIControlStateNormal];
        [buyButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
        [buyButton setBackgroundColor:ColorWithRGB(0xFFE055)];
    }
    
    
    [buyButton setTitleColor:ZRWhiteColor forState:UIControlStateSelected];
    [buyButton addTarget:self action:@selector(clickBuyButton) forControlEvents:UIControlEventTouchUpInside];
    buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:18 * SCREENH6];
    
    self.buyButton = buyButton;
    
    [self.view addSubview:self.buyButton];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (tableView == self.tableView) {
        
        return 3;
    }else{
        
        return 1;
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        if (section == 0) {
            
            return [self.momentList count];
        }else{
            
            return 1;
        }
    }else{
        
        if (self.couponArray.count == 0) {
            
            self.showLabel.hidden = NO;
        }else{
            
            self.showLabel.hidden = YES;
        }
        
        
        return self.couponArray.count;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (tableView == self.tableView) {
        
        if (indexPath.section == 0) {
            
            MomentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsDetailCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (indexPath.row < 2) {
                cell.moment = [self.momentList objectAtIndex:indexPath.row];
                cell.delegate = self;
            }
            cell.type = @"goods";
            return cell;
        }else if (indexPath.section == 1){
            
            GoodsInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsInfoTableViewCell" forIndexPath:indexPath];
            
            cell.dict = self.dataDict;
            
            return cell;
        }else{
            
            MapTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MapTableViewCell" forIndexPath:indexPath];
            
            if (self.local) {
                
                cell.local = self.local;
            }
            
            return cell;
        }
    }else{
        
        NewCouponTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsCouponTableViewCell" forIndexPath:indexPath];
        
        cell.model = self.couponArray[indexPath.row];
        cell.type = @"goods";
        
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.tableView) {
        
        if (indexPath.section == 0) {
            
            // 使用缓存行高，避免计算多次
            Moment *moment = [self.momentList objectAtIndex:indexPath.row];
            return moment.rowHeight;
        }else if (indexPath.section == 1) {
            
            //            return UITableViewAutomaticDimension;
            if (self.cellHeight) {
                //                NSLog(@"cellHeight===%f",self.cellHeight);
                return self.cellHeight;
            }else{
                
                return 135 * SCREENH6;
            }
            
        }else{
            
            return 180 * SCREENH6;
        }
    }else{
        
        return 105 * SCREENH6;
    }
    
    
}

//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//    if (tableView == self.tableView) {
//
//        if (indexPath.section == 1) {
//
//            return 300 * SCREENH6;
//        }else{
//
//            return 100;
//        }
//    }else{
//
//        return 105 * SCREENH6;
//    }
//
//}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.couponTableView) {
        
        CouponModel * model = self.couponArray[indexPath.row];
        
        NewCouponTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        
        if ([cell.editLabel.text isEqualToString:@"领取"]) {
            
            NSString * coupon_id = [NSString stringWithFormat:@"%@",model.id];
            
            [[ZRNetworkTool sharedTool] userReceiveMerchantsCouponsResultWithCoupon_id:coupon_id WithBlock:^(BOOL success, id responseData) {
                
                if (success) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:@"恭喜你，领取成功快去使用吧！"
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              NSString * merchants_goods_merchants_id = [NSString stringWithFormat:@"%@",self.dataDict[@"merchants_goods_merchants_id"]];
                                                                              
                                                                              [self loadCouponDataWithShop_id:merchants_goods_merchants_id];
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
        }
        
        
    }
}



#pragma mark - UITableViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSIndexPath *indexPath =  [self.tableView indexPathForRowAtPoint:CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y)];
}

#pragma mark - GoodsDetailsHeaderViewDelegate
- (void)clickUserImageButton:(NSString *)ID{
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    if ([user_id isEqualToString:ID]) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"你不能点击自己的头像"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        HiddenBar;
        
        PersonalViewController * personVC = [PersonalViewController new];
        personVC.ID = ID;
        
        [self.navigationController pushViewController:personVC animated:YES];
    }
    
    
}

- (void)clickMoreButton:(NSString *)type{
    
    if ([type isEqualToString:@"coupon"]) {
        
        [self setupCouponView];
    }else if ([type isEqualToString:@"commit"]){
        
        HiddenBar;
        
        CommitDetailsViewController * detailVC = [CommitDetailsViewController new];
        
        detailVC.ID = self.ID;
        
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (void)pushToMapViewConteoller{
    
    HiddenBar;
    
    MapViewController * mapVC = [MapViewController new];
    
    mapVC.merchants_latitude = self.merchants_latitude;
    mapVC.merchants_longitude = self.merchants_longitude;
    mapVC.merchants_name = self.merchants_name;
    mapVC.merchants_local = self.merchants_local;
    
    [self.navigationController pushViewController:mapVC animated:YES];
}

- (UIButton *)setupButtonWithImage:(NSString *)image{
    
    UIButton * button = [UIButton new];
    
    [button setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickNavButton:) forControlEvents:UIControlEventTouchUpInside];
    
    
    return button;
}


- (void)clickBuyButton{
    
    if ([self.state isEqualToString:@"create"]) {
        
        if (self.timeString && self.dateString) {
            
            self.orderTimeString = [NSString stringWithFormat:@"%@ %@",self.dateString,self.timeString];
            
            HiddenBar;
            CreateActiveDetailsViewController * createVC = [CreateActiveDetailsViewController new];
            
            createVC.dict = self.dataDict;
            createVC.dateString = self.orderTimeString;
            createVC.group_id = self.group_id;
            
            [self.navigationController pushViewController:createVC animated:YES];       
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"请先选择团购场次"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
    }else{
        
        if (self.buyButton.selected) {
            
            [[ZRNetworkTool sharedTool] setOpenGroupRemindedWithGoods_id:self.ID ResultWithBlock:^(BOOL success, id responseData) {
                
                if (success) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              [self.buyButton setTitle:@"已预约" forState:UIControlStateNormal];
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
        }else{
            
            int merchants_goods_is_need_insurance = [self.dataDict[@"merchants_goods_is_need_insurance"] intValue];

            if (merchants_goods_is_need_insurance == 1) {
                //官方活动
                
                UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
                //样式
                toolbar.barStyle = UIBarStyleBlackTranslucent;//半透明
                //透明度
                toolbar.alpha = 0.5f;
                toolbar.userInteractionEnabled = YES;
                UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeFinishView)];
                [toolbar addGestureRecognizer:tapGR];
                
                self.finishToolbar = toolbar;
                
                [self.tabBarController.view addSubview:self.finishToolbar];
                
                self.finishView = [[FinishPersonalView alloc] initWithFrame:CGRectMake(15 * SCREENH6, 0, 345 * SCREENH6, 275 * SCREENH6)];
                
                self.finishView.backgroundColor = ZRWhiteColor;
                self.finishView.layer.cornerRadius = 5 * SCREENH6;
                self.finishView.layer.masksToBounds = YES;
                self.finishView.delegate = self;
                
                self.finishView.centerY = self.view.centerY;
                
                [self.tabBarController.view addSubview:self.finishView];
            }else{
                
                [self clickNextButton];
            }
        
        }
    }
}


- (void)clickNavButton:(UIButton *)button{
    
    if (button == self.backButton) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }else if (button == self.collectButton){
        
        if (button.selected) {
            
            //获取当前时间日期
            NSDate *date=[NSDate date];
            NSDateFormatter *format1=[[NSDateFormatter alloc] init];
            [format1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *dateStr;
            dateStr=[format1 stringFromDate:date];
            
            NSString * user_id = DEF_GET_OBJECT(@"id");
            
            NSDictionary * dict = @{@"timeStamp":dateStr,@"goods_id":self.ID,@"user_id":user_id};
            
            NSString * sign = [self signStr:dict];
            
            NSDictionary * resDict = @{@"timeStamp":dateStr,@"sign":sign,@"goods_id":self.ID,@"user_id":user_id};
            
            [[NetworkTool sharedTools] POST:@"Api/userCancelCollectionGoods" parameters:resDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
                
                int code = [responseObject[@"code"] intValue];
                
                if (code == 200) {
                    
                    self.collectButton.selected = NO;
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            
        }else{
            
            //获取当前时间日期
            NSDate *date=[NSDate date];
            NSDateFormatter *format1=[[NSDateFormatter alloc] init];
            [format1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *dateStr;
            dateStr=[format1 stringFromDate:date];
            
            NSString * user_id = DEF_GET_OBJECT(@"id");
            
            NSDictionary * dict = @{@"timeStamp":dateStr,@"goods_id":self.ID,@"user_id":user_id};
            
            NSString * sign = [self signStr:dict];
            
            NSDictionary * resDict = @{@"timeStamp":dateStr,@"sign":sign,@"goods_id":self.ID,@"user_id":user_id};
            
            [[NetworkTool sharedTools] POST:@"Api/userCollectionGoods" parameters:resDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
                
                //                NSLog(@"coll====%@",responseObject);
                int code = [responseObject[@"code"] intValue];
                
                if (code == 200) {
                    
                    self.collectButton.selected = YES;
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }
        
    }else if (button == self.shareButton){
        
        
        [self setupShareView];
    }
}


- (void)setupShareView{
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //样式
    toolbar.barStyle = UIBarStyleBlackTranslucent;//半透明
    //透明度
    toolbar.alpha = 0.5f;
    toolbar.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [toolbar addGestureRecognizer:tapGR];
    
    self.shareToolbar = toolbar;
    [self.tabBarController.view addSubview:self.shareToolbar];
    
    UIView * shareView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH - 155 * SCREENH6, kScreenW, 155 * SCREENH6)];
    
    shareView.backgroundColor = ZRWhiteColor;
    shareView.userInteractionEnabled = YES;
    
    self.shareView = shareView;
    
    [self.tabBarController.view addSubview:self.shareView];
    
    
    UIButton * weixinButton = [UIButton new];
    
    weixinButton.tag = 1001;
    [weixinButton setImage:[UIImage imageNamed:@"微信好友"] forState:UIControlStateNormal];
    [weixinButton addTarget:self action:@selector(clickShareButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.shareView addSubview:weixinButton];
    
    UIButton * friendButton = [UIButton new];
    
    friendButton.tag = 1002;
    [friendButton setImage:[UIImage imageNamed:@"微信朋友圈"] forState:UIControlStateNormal];
    [friendButton addTarget:self action:@selector(clickShareButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.shareView addSubview:friendButton];
    
    
    [weixinButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(80 * SCREENH6);
        make.centerY.mas_equalTo(self.shareView);
        make.width.mas_equalTo(56 * SCREENH6);
        make.height.mas_equalTo(74 * SCREENH6);
    }];
    
    [friendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.view).offset(-80 * SCREENH6);
        make.centerY.mas_equalTo(self.shareView);
        make.width.mas_equalTo(69 * SCREENH6);
        make.height.mas_equalTo(74 * SCREENH6);
    }];
}


- (void)tapAction{
    
    [self.shareToolbar removeFromSuperview];
    [self.shareView removeFromSuperview];
}

- (void)clickShareButton:(UIButton *)button{
    
    [self.shareToolbar removeFromSuperview];
    [self.shareView removeFromSuperview];
    
    ShowHUD;
    
    NSString * merchants_goods_category = [NSString stringWithFormat:@"%@",self.dataDict[@"merchants_goods_category"]];
    
    [[ZRNetworkTool sharedTool] getUserShareSystemWithCategory_id:merchants_goods_category ResultWithBlock:^(BOOL success, id responseData) {
        
        HiddenHUD;
        if (success) {
            
            NSDictionary * dict = responseData[@"data"];
            
            NSString * kLinkURL = [NSString stringWithFormat:@"%@?good_id=%@?distance=%@",dict[@"url"],self.dataDict[@"id"],self.distance];
            
            NSString *kLinkTitle = dict[@"title"];
            NSString *kLinkDescription = dict[@"info"];
            NSString * imgStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,dict[@"img"]];
            NSURL * url = [NSURL URLWithString:imgStr];
            NSData * data = [NSData dataWithContentsOfURL:url];
            UIImage * img = [UIImage imageWithData:data];
            
            SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
            
            // 是否是文档
            req1.bText =  NO;
            
            //    WXSceneSession  = 0,        /**< 聊天界面    */
            //    WXSceneTimeline = 1,        /**< 朋友圈      */
            //    WXSceneFavorite = 2,
            
            
            if (button.tag == 1001) {
                
                req1.scene = WXSceneSession;
                
                //创建分享内容对象
                WXMediaMessage *urlMessage = [WXMediaMessage message];
                urlMessage.title = kLinkTitle;//分享标题
                urlMessage.description = kLinkDescription;//分享描述
                [urlMessage setThumbImage:img];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
                
                //创建多媒体对象
                WXWebpageObject *webObj = [WXWebpageObject object];
                webObj.webpageUrl = kLinkURL;//分享链接
                
                //完成发送对象实例
                urlMessage.mediaObject = webObj;
                req1.message = urlMessage;
                
                //发送分享信息
                [WXApi sendReq:req1];
            }else if (button.tag == 1002) {
                
                req1.scene = WXSceneTimeline;
                
                //创建分享内容对象
                WXMediaMessage *urlMessage = [WXMediaMessage message];
                urlMessage.title = kLinkTitle;//分享标题
                urlMessage.description = kLinkDescription;//分享描述
                [urlMessage setThumbImage:img];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
                
                //创建多媒体对象
                WXWebpageObject *webObj = [WXWebpageObject object];
                webObj.webpageUrl = kLinkURL;//分享链接
                
                //完成发送对象实例
                urlMessage.mediaObject = webObj;
                req1.message = urlMessage;
                
                //发送分享信息
                [WXApi sendReq:req1];
            }
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
    //分享积分
    [[ZRNetworkTool sharedTool] shareIntegralWithBlock:^(BOOL success, id responseData) {
        
//        NSLog(@"分享积分====%@",responseData);
    }];
    
}

- (void)setupCouponView{
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //样式
    toolbar.barStyle = UIBarStyleBlackTranslucent;//半透明
    //透明度
    toolbar.alpha = 0.5f;
    toolbar.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenCouponView)];
    [toolbar addGestureRecognizer:tapGR];
    
    self.toolbar = toolbar;
    [self.tabBarController.view addSubview:self.toolbar];
    
    UIView * couponView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH - 300 * SCREENH6, kScreenW, 300 * SCREENH6)];
    
    couponView.backgroundColor = ZRWhiteColor;
    couponView.userInteractionEnabled = YES;
    
    self.couponView = couponView;
    
    [self.tabBarController.view addSubview:self.couponView];
    
    
    UIButton * closeButton = [UIButton new];
    
    [closeButton setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(clickCloseButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.couponView addSubview:closeButton];
    
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.text = @"优惠详情";
    titleLabel.textColor = ZRBlackColor;
    titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    
    [self.couponView addSubview:titleLabel];
    
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    [self.couponView addSubview:lineView];
    
    
    UILabel * showLabel = [UILabel new];
    
    showLabel.text = @"暂无优惠券";
    showLabel.textColor = ZRBlackColor;
    showLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    showLabel.hidden = YES;
    
    self.showLabel = showLabel;
    
    [self.couponView addSubview:self.showLabel];
    
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40 * SCREENH6, kScreenW, 270 * SCREENH6) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor clearColor];
    //    tableView.rowHeight = 105 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.couponTableView = tableView;
    
    [self.couponTableView registerClass:[NewCouponTableViewCell class] forCellReuseIdentifier:@"GoodsCouponTableViewCell"];
    
    [self.couponView addSubview:self.couponTableView];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.couponView);
        make.top.mas_equalTo(self.couponView).offset(10 * SCREENH6);
    }];
    
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.couponView).offset(-10 * SCREENH6);
        make.centerY.mas_equalTo(titleLabel);
        make.width.height.mas_equalTo(15 * SCREENH6);
    }];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.couponView);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(self.couponView).offset(40 * SCREENH6);
    }];
    
    [self.showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.couponTableView);
        make.centerY.mas_equalTo(self.couponTableView);
    }];
}

- (void)clickCloseButton{
    
    [self.toolbar removeFromSuperview];
    [self.couponView removeFromSuperview];
    [self.couponTableView removeFromSuperview];
}

- (void)hiddenCouponView{
    
    [self.toolbar removeFromSuperview];
    [self.couponView removeFromSuperview];
    [self.couponTableView removeFromSuperview];
}

- (void)pushToCalendarView{
    
    if ([self.start isEqualToString:@"noStart"]) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"拼团尚未开始"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        HiddenBar;
        
        NSArray * weekArray = self.dataDict[@"merchants_goods_available_time_weeks"];
        NSString * date = [NSString stringWithFormat:@"%@",self.dataDict[@"merchants_goods_end_time"]];
        
        CalenderViewController * calenderVC = [CalenderViewController new];
        
        calenderVC.calenderViewControllerDelegate = self;
        calenderVC.weekdayArray = weekArray;
//        NSLog(@"weekArray==%@",weekArray);
        calenderVC.dateStr = date;
        
        [self.navigationController pushViewController:calenderVC animated:YES];
    }
    
}

- (void)clickDateButton:(NSString *)date{
    
    [[ZRNetworkTool sharedTool] getMerchantsGoodsFieldResultWithGoodsId:self.ID WithChoose_date:date WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            self.tuanArray = [NSArray yy_modelArrayWithClass:[ShowTuanWeek class] json:responseData[@"data"]];
        }
    }];
    
    
    self.dateString = date;
}

- (void)clickTuanMoreButton:(NSNotification *)noti{
    
    NSString * type = noti.userInfo[@"type"];
    
    if ([type isEqualToString:@"coupon"]) {
        
        [self setupCouponView];
    }else if ([type isEqualToString:@"commit"]){
        
        HiddenBar;
        
        CommitDetailsViewController * detailVC = [CommitDetailsViewController new];
        
        detailVC.ID = self.ID;
        
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


- (void)updateSelectTime:(NSNotification *)noti{
    
    NSString * time = noti.userInfo[@"time"];
    self.timeString = time;
}

- (void)PushToChat{
    
    NSString * merchants_admin_phone = self.dataDict[@"merchants_admin_phone"];
    
    [JMSGConversation createSingleConversationWithUsername:merchants_admin_phone completionHandler:^(id resultObject, NSError *error) {
        
        if (error == nil) {
            HiddenBar;
            ChatRoomViewController * roomVC = [ChatRoomViewController new];
            
            roomVC.conversation = resultObject;
            
            [self.navigationController pushViewController:roomVC animated:YES];
            
        } else {
            
        }
    }];
}


- (void)showAlertView{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@"您不能和自己聊天"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)changeCellHeight:(NSNotification *)noti{
    
    self.cellHeight = [noti.userInfo[@"height"] floatValue] + 70 * SCREENH6;
    
    [self.tableView reloadData];
}

- (void)pushToPersonal:(NSNotification *)noti{
    
    NSString * ID = noti.userInfo[@"id"];
    NSString * user_id = DEF_GET_OBJECT(@"id");
    if ([user_id isEqualToString:ID]) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"你不能点击自己的头像"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        HiddenBar;
        
        PersonalViewController * personVC = [PersonalViewController new];
        personVC.ID = ID;
        
        [self.navigationController pushViewController:personVC animated:YES];
    }
    
}

- (void)clickButtonWithType:(NSString *)type WithDict:(NSDictionary *)dict{
    
    if ([type isEqualToString:@"sure"]) {
        
        if ([self.finishView.ID isEqualToString:@"yes"]) {
            
            [self.finishView removeFromSuperview];
            [self.finishToolbar removeFromSuperview];
            
            [self clickNextButton];
        }else{
            
            [[ZRNetworkTool sharedTool] updateUserInfoAllWithDict:dict WithBlock:^(BOOL success, id responseData) {
                
                if (success) {
                    
                    [self clickNextButton];
                    
                    [self.finishView removeFromSuperview];
                    [self.finishToolbar removeFromSuperview];
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
        }
        
    }else if([type isEqualToString:@"cancel"]){
        
        
    }
    
    
    
}


- (void)firstFinishPersonalInfo{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@"请先完善个人信息"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)removeFinishView{
    
    [self.finishView removeFromSuperview];
    [self.finishToolbar removeFromSuperview];
}


- (void)clickNextButton{
    
    //获取当前时间日期
    NSDate *date=[NSDate date];
    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    NSDateFormatter *format2=[[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [format2 setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr;
    dateStr=[format1 stringFromDate:date];
    NSString * nowDateStr = [format2 stringFromDate:date];
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    if ([self.infoType isEqualToString:@"1"]) {
        
        NSDictionary * dict = @{@"timeStamp":dateStr,@"goods_order_goods_id":self.ID,@"goods_order_user_id":user_id};
        
        NSString * sign = [self signStr:dict];
        
        NSDictionary * resDict = @{@"timeStamp":dateStr,@"sign":sign,@"goods_order_goods_id":self.ID,@"goods_order_user_id":user_id};
        
        [[NetworkTool sharedTools] POST:@"Api/buyMerchantsGoods" parameters:resDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            int code = [responseObject[@"code"] intValue];
            
            if (code == 200) {
                NSDictionary * data = responseObject[@"data"];
                NSString * goodsID = data[@"id"];
                HiddenBar;
                NormalSureOrderViewController * sureVC = [NormalSureOrderViewController new];
                sureVC.orderID = goodsID;
                sureVC.dict = self.dataDict;
                [self.navigationController pushViewController:sureVC animated:YES];
                
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }else if ([self.infoType isEqualToString:@"2"]){
//
        if (self.is_official == 0) {
            
            if (self.timeString && self.dateString) {
                
                self.orderTimeString = [NSString stringWithFormat:@"%@ %@",self.dateString,self.timeString];
                
                if ([self.dateString isEqualToString:nowDateStr]) {
                    
                    NSDictionary * dict = @{@"timeStamp":dateStr,@"goods_order_goods_id":self.ID,@"goods_order_user_id":user_id,@"goods_order_goods_field":self.orderTimeString};
                    
                    NSString * sign = [self signStr:dict];
                    
                    NSDictionary * resDict = @{@"timeStamp":dateStr,@"sign":sign,@"goods_order_goods_id":self.ID,@"goods_order_user_id":user_id,@"goods_order_goods_field":self.orderTimeString};
                    
                    [[NetworkTool sharedTools] POST:@"Api/buyMerchantsGoods" parameters:resDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
                        
                        int code = [responseObject[@"code"] intValue];
                        
                        if (code == 200) {
                            NSDictionary * data = responseObject[@"data"];
                            NSString * goodsID = data[@"id"];
                            HiddenBar;
                            SureOrderViewController * sureVC = [SureOrderViewController new];
                            sureVC.orderID = goodsID;
                            sureVC.dict = self.dataDict;
                            sureVC.time = self.orderTimeString;
                            [self.navigationController pushViewController:sureVC animated:YES];
                        }else{
                            
                            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                           message:responseObject[@"message"]
                                                                                    preferredStyle:UIAlertControllerStyleAlert];
                            
                            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                                  handler:^(UIAlertAction * action) {
                                                                                      
                                                                                  }];
                            
                            [alert addAction:defaultAction];
                            [self presentViewController:alert animated:YES completion:nil];
                        }
                        
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        
                    }];
                    
                }else{
                    
                    NSString * showStr = [NSString stringWithFormat:@"您确定购买%@该场次",self.orderTimeString];
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:showStr
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                                          handler:^(UIAlertAction * action) {
                                                                              NSDictionary * dict = @{@"timeStamp":dateStr,@"goods_order_goods_id":self.ID,@"goods_order_user_id":user_id,@"goods_order_goods_field":self.orderTimeString};
                                                                              
                                                                              NSString * sign = [self signStr:dict];
                                                                              
                                                                              NSDictionary * resDict = @{@"timeStamp":dateStr,@"sign":sign,@"goods_order_goods_id":self.ID,@"goods_order_user_id":user_id,@"goods_order_goods_field":self.orderTimeString};
                                                                              
                                                                              [[NetworkTool sharedTools] POST:@"Api/buyMerchantsGoods" parameters:resDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
                                                                                  
                                                                                  int code = [responseObject[@"code"] intValue];
                                                                                  
                                                                                  if (code == 200) {
                                                                                      NSDictionary * data = responseObject[@"data"];
                                                                                      NSString * goodsID = data[@"id"];
                                                                                      HiddenBar;
                                                                                      SureOrderViewController * sureVC = [SureOrderViewController new];
                                                                                      sureVC.orderID = goodsID;
                                                                                      sureVC.dict = self.dataDict;
                                                                                      sureVC.time = self.orderTimeString;
                                                                                      [self.navigationController pushViewController:sureVC animated:YES];
                                                                                  }else{
                                                                                      
                                                                                      UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                                                                                     message:responseObject[@"message"]
                                                                                                                                              preferredStyle:UIAlertControllerStyleAlert];
                                                                                      
                                                                                      UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                                                                                            handler:^(UIAlertAction * action) {
                                                                                                                                                
                                                                                                                                            }];
                                                                                      
                                                                                      [alert addAction:defaultAction];
                                                                                      [self presentViewController:alert animated:YES completion:nil];
                                                                                  }
                                                                                  
                                                                              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                                                  
                                                                              }];
                                                                          }];
                    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                                         handler:^(UIAlertAction * action) {
                                                                             
                                                                         }];
                    
                    [alert addAction:defaultAction];
                    [alert addAction:cancelAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:@"请先选择团购场次"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }

        }else{
            
            self.orderTimeString = self.merchants_goods_field_time;
            NSDictionary * dict = @{@"timeStamp":dateStr,@"goods_order_goods_id":self.ID,@"goods_order_user_id":user_id,@"goods_order_goods_field":self.orderTimeString};
            
            NSString * sign = [self signStr:dict];
            
            NSDictionary * resDict = @{@"timeStamp":dateStr,@"sign":sign,@"goods_order_goods_id":self.ID,@"goods_order_user_id":user_id,@"goods_order_goods_field":self.orderTimeString};
            
            [[NetworkTool sharedTools] POST:@"Api/buyMerchantsGoods" parameters:resDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
                
                int code = [responseObject[@"code"] intValue];
                
                if (code == 200) {
                    NSDictionary * data = responseObject[@"data"];
                    NSString * goodsID = data[@"id"];
                    HiddenBar;
                    SureOrderViewController * sureVC = [SureOrderViewController new];
                    sureVC.orderID = goodsID;
                    sureVC.dict = self.dataDict;
                    sureVC.time = self.orderTimeString;
                    [self.navigationController pushViewController:sureVC animated:YES];
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseObject[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            
        }
    }

}


- (NSString *)signStr:(NSDictionary *)dict{
    
    NSArray *keyArray = [dict allKeys];
    
    //定义一个排序数组，存储排序好之后的key值
    NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    //这时我们再创建一个数组，来按升序存储key对应的Value，通过遍历sortArray的方法
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortString in sortArray) {
        [valueArray addObject:[dict objectForKey:sortString]];
    }
    //    现在我们有两个数组，分别对应升序排序的key和value，所以再创建一个keyValue的数组来存储每一个key和value的格式
    //    NSMutableArray *signArray = [NSMutableArray array];
    //    for (int i = 0; i < sortArray.count; i++) {
    //        NSString *keyValueStr = [NSString stringWithFormat:@"%@:%@",sortArray[i],valueArray[i]];
    //        [signArray addObject:keyValueStr];
    //    }
    
    //最后的一步，就是用“,”把每个字符串拼接起来
    NSString *sign = [valueArray componentsJoinedByString:@""];
    
    NSString * resStr = [NSString stringWithFormat:@"%@NDQ0NTlmMDk4MTU3NTg3NzFiZTFlZmQwNDFjNzA0ZGMyYWY0NzU5ZQ==",sign];
    
    NSString *signStr = [self md5:resStr];
    
    NSString * baseStr = [self encode:signStr];
    
    return baseStr;
}

- (NSString *) md5:(NSString *) str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (NSString *)encode:(NSString *)string
{
    //先将string转换成data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *base64Data = [data base64EncodedDataWithOptions:0];
    
    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    
    return baseString;
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//#pragma mark - TableView 占位图
//- (NSString *)xy_noDataViewMessage {
//
//    return @"";
//}
//
//- (UIColor *)xy_noDataViewMessageColor {
//
//    return [UIColor blackColor];
//}

/**
 *  获取当天的字符串
 *  @return 格式为年-月-日 时分秒
 */
- (NSString *)getCurrentTimeyyyymmdd {
    
    NSDate *now = [NSDate date];
    NSDateFormatter *formatDay = [[NSDateFormatter alloc] init];
    formatDay.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *dayStr = [formatDay stringFromDate:now];
    
    return dayStr;
}

/**
 *  获取时间差值  截止时间-当前时间
 *  nowDateStr : 当前时间
 *  deadlineStr : 截止时间
 *  @return 时间戳差值
 */
- (NSInteger)getDateDifferenceWithNowDateStr:(NSString*)nowDateStr deadlineStr:(NSString*)deadlineStr {
    
    NSInteger timeDifference = 0;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yy-MM-dd HH:mm:ss"];
    NSDate *nowDate = [formatter dateFromString:nowDateStr];
    NSDate *deadline = [formatter dateFromString:deadlineStr];
    NSTimeInterval oldTime = [nowDate timeIntervalSince1970];
    NSTimeInterval newTime = [deadline timeIntervalSince1970];
    timeDifference = newTime - oldTime;
    
    return timeDifference;
}

-(double)distanceBetweenOrderBy:(double) lat1 :(double) lat2 :(double) lng1 :(double) lng2{
    
    CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
    
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
    
    double  distance  = [curLocation distanceFromLocation:otherLocation];
    
    return  distance;
    
}

- (void)pushToMapView{
    
    HiddenBar;
    
    MapViewController * mapVC = [MapViewController new];
    
    mapVC.merchants_latitude = self.merchants_latitude;
    mapVC.merchants_longitude = self.merchants_longitude;
    mapVC.merchants_name = self.merchants_name;
    mapVC.merchants_local = self.merchants_local;
    
    [self.navigationController pushViewController:mapVC animated:YES];
}


@end
